/**
 * Carnegie Mellon University
 * School of Computer Science
 * MSIT eBusiness Technology
 * 
 * Team 8 - Infinity (2011 Spring)
 * infinity-team8@googlegroups.com
 * 
 * Professor: Jeffrey L. Eppinger
 * Program Faculty: Sujata Telang
 */

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import databean.CustomerBean;
import databean.EmployeeBean;


public class Controller extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {
        Model model = new Model(getServletConfig());

        //Customer
        Action.add(new CustomerLoginAction(model));
        Action.add(new CustomerChangePwdAction(model));
        Action.add(new CustomerViewAccountAction(model));
        Action.add(new CustomerTransactionHistoryAction(model));
        Action.add(new CustomerLogoutAction(model));
        Action.add(new CustomerRequestCheckAction(model));
        Action.add(new CustomerBuyFundAction(model));
        Action.add(new CustomerSellFundAction(model));
        Action.add(new CustomerResearchFundAction(model));
        //Employee
        Action.add(new EmployeeLoginAction(model));
        Action.add(new EmployeeChangePwdAction(model));
        Action.add(new EmployeeLogoutAction(model));
        Action.add(new EmployeeViewAccountAction(model));
        Action.add(new EmployeeCreateEmployeeAccountAction(model));
        Action.add(new EmployeeCreateCustomerAccountAction(model));
        Action.add(new EmployeeResetCustomerPasswordAction(model));
        Action.add(new EmployeeCreateFundAction(model));
        Action.add(new EmployeeViewFundsAction(model));
        Action.add(new EmployeeViewEmployeeListAction(model));
        Action.add(new EmployeeViewCustomerAccountAction(model));
        Action.add(new EmployeeTransactionHistoryAction(model));
        Action.add(new EmployeeFundPriceHistoryAction(model));
        Action.add(new EmployeeTransitionDayAction(model));
        Action.add(new EmployeeDepositCheckAction(model));
        //WS
        Action.add(new GetFundPriceHistoryAction(model));
        Action.add(new GetTransactionAction(model));
        Action.add(new GetRecommendAction(model));
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nextPage = performTheAction(request, response);
        sendToNextPage(nextPage,request,response);
    }
    
    /*
     * Extracts the requested action and (depending on whether the user is logged in)
     * perform it (or make the user login).
     * @param request
     * @return the next page (the view)
     */
    private String performTheAction(HttpServletRequest request,HttpServletResponse response) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        CustomerBean    customer = (CustomerBean) session.getAttribute("customer");
        EmployeeBean    employee = (EmployeeBean) session.getAttribute("employee");
        String      action = getActionName(servletPath);
        
        
        if ( ( action.startsWith("customer") ) && (customer == null) ) {
        	// If the user hasn't logged in, direct him to the login page
        	return Action.perform("customer-login.do",request, response);
        }

        
        if ( ( action.startsWith("employee") ) && (employee == null) ) {
        	// If the user hasn't logged in, direct him to the login page
			return Action.perform("employee-login.do",request, response);
        }
        
        
        if (action.equals("start")) {
        	// If he's logged in but back at the /start page, send him to manage his pics
			return Action.perform("customer-manage.do",request, response);
        }

      	// Let the logged in user run his chosen action
		return Action.perform(action,request,response);
    }
    
    /*
     * If nextPage is null, send back 404
     * If nextPage starts with a '/', redirect to this page.
     *    In this case, the page must be the whole servlet path including the webapp name
     * Otherwise dispatch to the page (the view)
     *    This is the common case
     * Note: If nextPage equals "image", we will dispatch to /image.  In the web.xml file, "/image"
     *    is mapped to the ImageServlet will which return the image bytes for display.
     */
    private void sendToNextPage(String nextPage, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	
    	if (nextPage == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	
    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	
    	
    	
   		RequestDispatcher d = request.getRequestDispatcher("/WEB-INF/view/"+nextPage);
   		d.forward(request,response);
    }

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
    private String getActionName(String path) {
    	// We're guaranteed that the path will start with a slash
        int slash = path.lastIndexOf('/');
        return path.substring(slash+1);
    }
}
